package com.example.ruiji.utils.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.example.ruiji.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import java.util.Date;
import java.util.UUID;

/**
 * Author:BaiYiChen
 * Date:2022/5/2 19:28
 *
 * @author BaiYiChen
 */
public class MyTokenUtils {
  /**
   *
   * @value ACCESS_TOKEN 返回给前端的token的Key
   *        EXPIRE_SECONDS 过期时间
   *        SECRET_ 密钥
   *        user  保存登录用户
   */
  public static final String ACCESS_TOKEN = "access_token";
  public static final Long EXPIRE_SECONDS = 24 * 60 * 60 * 1000L;
  private static final String SECRET_ = "ABCDEFG";
  public static User user;
  
  /**
   *
   * @param account 用户
   * @param salt 用户对应加密盐
   * @return 用户名加盐值加密得到的accessToken字符串
   */
  public static String createToken(String account, String salt) {
    Algorithm hmac256 = Algorithm.HMAC256(salt);
    
    return JWT.create().withClaim("username", account)
            .withClaim("salt", salt)
            .withJWTId(UUID.randomUUID().toString())
            .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_SECONDS))
            .sign(hmac256);
  }
  
  public static String getAccount(String accessToken) {
    return JWT.decode(accessToken).getClaim("username").asString();
  }
  
  public static String getSalt(String accessToken) {
  
    return JWT.decode(accessToken).getClaim("salt").asString();
  }
  
  /**
   *
   * @param accessToken 要验证的token
   * @param account token 里对应的账户名
   * @param salt token里的加密盐
   * @return 是否校验成功
   */
  public static boolean verifiedToken(String accessToken, String account, String salt) {
    Algorithm hmac256 = Algorithm.HMAC256(salt);
    JWTVerifier verifier = JWT.require(hmac256)
            .withClaim("username", account)
            .withClaim("salt", salt)
            .build();
    try {
      verifier.verify(accessToken);
    } catch (Exception e) {
      throw new RuntimeException("token验证不通过");
    }
    return true;
  }
}
